from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.db.database import get_db
from app.core.security import (
    verify_password,
    create_access_token,
    get_current_user
)
from app.core.exceptions import (
    InvalidCredentialsError,
    UserBannedError,
    UserNotFoundError
)
from app.models.user import User, UserType
from app.schemas.user import UserLogin, WechatLogin, Token, TokenData
from app.utils.wechat import get_wechat_openid

router = APIRouter(prefix="/auth", tags=["认证"])

@router.post("/wechat", response_model=Token)
async def wechat_login(
    login_data: WechatLogin,
    db: AsyncSession = Depends(get_db)
):
    openid = await get_wechat_openid(login_data.code)
    
    # 查找或创建用户
    result = await db.execute(select(User).where(User.openid == openid))
    user = result.scalar_one_or_none()
    
    if not user:
        user = User(
            openid=openid,
            username=f"user_{openid[:8]}",
            nickname=f"用户_{openid[:8]}",
            user_type=UserType.USER
        )
        db.add(user)
        await db.commit()
        await db.refresh(user)
    
    if not user.is_active:
        raise UserBannedError()
    
    access_token = create_access_token(
        data={
            "sub": user.username,
            "user_type": user.user_type.value,
            "permission_level": user.permission_level
        }
    )
    return Token(access_token=access_token)

@router.post("/admin", response_model=Token)
async def admin_login(
    login_data: UserLogin,
    db: AsyncSession = Depends(get_db)
):
    result = await db.execute(
        select(User).where(User.username == login_data.username)
    )
    user = result.scalar_one_or_none()
    
    if not user or not verify_password(login_data.password, user.password):
        raise InvalidCredentialsError()
    
    if not user.is_active:
        raise UserBannedError()
    
    if user.user_type != UserType.ADMIN:
        raise InvalidCredentialsError()
    
    access_token = create_access_token(
        data={
            "sub": user.username,
            "user_type": user.user_type.value,
            "permission_level": user.permission_level
        }
    )
    return Token(access_token=access_token)

@router.get("/check-login")
async def check_login(
    current_user: TokenData = Depends(get_current_user)
):
    return {"code": 10000, "data": "success"} 